import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { fetchUserInfo } from '@/api'

export const useUserStore = defineStore('user', () => {
  const initData = {
    id: 0,
    phone: '',
    username: '',
    head_img: '',
    authorize: -1,
    organization_name: ''
  }
  const userInfo = ref({ ...initData })

  const hasToken = ref(!!uni.getStorageSync('token'))

  const role = computed(() => getUserRole(userInfo.value.authorize))

  // 获取用户角色的辅助函数
  function getUserRole(authorize) {
    if (userInfo.value.register_method == 1) return '游客'
    switch (authorize) {
      case 0:
      case 1:
        return '超级管理员'
      case 2:
        return '公司售后管理员'
      case 3:
        return '代理商管理员'
      case 4:
        return '甲方区域管理员'
      case 5:
        return '巡检人员'
      case 6:
        return '安装人员'
      case 7:
        return '志愿者'
      case 9:
        return '测试其他'
      default:
        return '未知身份' // 或抛出异常等，视具体情况而定
    }
  }

  /**
   * 获取用户信息
   */
  async function getUserInfo() {
    if (uni.getStorageSync('token')) {
      await fetchUserInfo().then(res => (userInfo.value = res))
    }
  }

  function login(res) {
    uni.setStorageSync('token', res.token)
    hasToken.value = true
    userInfo.value = res
    uni.reLaunch({
      url: '/pages/profile/index'
    })
  }

  function logout() {
    uni.removeStorageSync('token')
    hasToken.value = false
    userInfo.value = { ...initData }
  }

  return {
    userInfo,
    role,
    hasToken,
    getUserInfo,
    login,
    logout
  }
})
